<?php

class FuturesController extends AppController {

    var $name = 'Futures';
    var $uses = array('Future', 'Job', 'Costume', 'Employee', 'Show', 'Production', 'Provider', 'Service', 'JobsDetail', 'JobsDetailsEmployee', 'Theater', 'Anotation');

    function index() {

        $this->Job->recursive = 0;
        $this->Theater->recursive = 1;

        $sql_jobs = "SELECT *
                FROM jobs as Job
                LEFT JOIN jobs_details as JobsDetail ON Job.id = JobsDetail.job_id
                LEFT JOIN jobs_details_employees as JobsDetailsEmployee ON JobsDetail.id = JobsDetailsEmployee.jobs_detail_id
                WHERE 1=1";

        $filtro_jobs = '';
        $filtro_theaters = '';
        $filtro_anotations = '';
        $fecha_min = '';
        $fecha_max = '';

        //si vienen filtros aplicados
        if (!empty($this->data)) {

            $datos = $this->data['Future'];

            if (isset($datos['pelotero_id']) && trim($datos['pelotero_id']) != '') {
                $filtro_jobs .= ' AND Job.pelotero_id = "' . $datos['pelotero_id'] . '"';
            }
            if (isset($datos['date_from']) && trim($datos['date_from']) != '') {
                list($d, $m, $a) = explode("/", $datos['date_from']);
                $datos['date_from'] = $a . "-" . $m . "-" . $d . ' 00:00:00';

                $filtro_jobs .= ' AND Job.start_date >= "' . $datos['date_from'] . '"';
                $filtro_theaters .= ' AND Theater.start_date >= "' . $datos['date_from'] . '"';
                $filtro_anotations .= ' AND Anotation.start_date >= "' . $datos['date_from'] . '"';
                $fecha_min = 'si';
            }
            if (isset($datos['date_to']) && trim($datos['date_to']) != '') {
                list($d, $m, $a) = explode("/", $datos['date_to']);
                $datos['date_to'] = $a . "-" . $m . "-" . $d . ' 23:59:59';

                $filtro_jobs .= ' AND Job.finish_date <= "' . $datos['date_to'] . '"';
                $filtro_theaters .= ' AND Theater.finish_date <= "' . $datos['date_to'] . '"';
                $filtro_anotations .= ' AND Anotation.finish_date <= "' . $datos['date_to'] . '"';
                $fecha_max = 'si';
            }

            //guardo el filtro usado en session para despues recordarlo
            $restricciones['Job'] = $filtro_jobs;
            $restricciones['Theater'] = $filtro_theaters;
            $restricciones['Anotation'] = $filtro_anotations;
            $restricciones['data'] = $this->data;
            $this->Session->write('search_conditions_future', $restricciones);
        } elseif ($this->Session->check('search_conditions_future')) {

            $restricciones = $this->Session->read('search_conditions_future');
            $filtro_jobs = $restricciones['Job'];
            $filtro_theaters = $restricciones['Theater'];
            $filtro_anotations = $restricciones['Anotation'];
            $this->data = $restricciones['data'];
            $datos = $this->data['Future'];

            if (isset($datos['date_from']) && trim($datos['date_from']) != '') {
                $fecha_min = 'si';
            }
            if (isset($datos['date_to']) && trim($datos['date_to']) != '') {
                $fecha_max = 'si';
            }
        }

        //si no viene ningun filtro de fecha, le pongo lo de la ultima semana
        if ($fecha_min != 'si' && $fecha_max != 'si') {
            $aux_fecha_min = date('Y-m-d 00:00:00');
            $aux_fecha_max = date('Y-m-d 23:59:59', strtotime('+6day', strtotime(date('Y-m-d H:i:s'))));
            $filtro_jobs .= ' AND Job.start_date >= "' . $aux_fecha_min . '"';
            $filtro_jobs .= ' AND Job.finish_date <= "' . $aux_fecha_max . '"';
            $filtro_theaters .= ' AND Theater.start_date >= "' . $aux_fecha_min . '"';
            $filtro_theaters .= ' AND Theater.finish_date <= "' . $aux_fecha_max . '"';
            $filtro_anotations .= ' AND Anotation.start_date >= "' . $aux_fecha_min . '"';
            $filtro_anotations .= ' AND Anotation.finish_date <= "' . $aux_fecha_max . '"';

            $this->data['Future']['date_from'] = date('d/m/Y', strtotime($aux_fecha_min));
            $this->data['Future']['date_to'] = date('d/m/Y', strtotime($aux_fecha_max));
        }

        $sql_jobs .= $filtro_jobs . ' order by Job.start_date ASC, Job.type DESC';
        
        $res_jobs = $this->Job->query($sql_jobs);

        //ahora armo bien el array de datos
        $array_jobs = array();
        foreach ($res_jobs as $job) {
            $job_id = $job['Job']['id'];
            $jobsdetail_id = $job['JobsDetail']['id'];
            $jobsdetailsemployee_id = $job['JobsDetailsEmployee']['id'];

            if (!isset($array_jobs[$job_id])) {
                $array_jobs[$job_id]['Job'] = $job['Job'];
            }

            if (!isset($array_jobs[$job_id]['Job']['JobsDetail'][$jobsdetail_id])) {
                $array_jobs[$job_id]['Job']['JobsDetail'][$jobsdetail_id] = $job['JobsDetail'];
            }

            if (!isset($array_jobs[$job_id]['Job']['JobsDetail'][$jobsdetail_id]['JobsDetailsEmployee'][$jobsdetailsemployee_id])) {
                $array_jobs[$job_id]['Job']['JobsDetail'][$jobsdetail_id]['JobsDetailsEmployee'][$jobsdetailsemployee_id] = $job['JobsDetailsEmployee'];
            }
        }
//        $this->set('jobs', $array_jobs);
        //obras de teatro
        $sql_theaters = 'SELECT *
                FROM theaters as Theater
                LEFT JOIN theaters_employees as TheatersEmployee ON Theater.id = TheatersEmployee.theater_id
                LEFT JOIN theaters_costumes as TheatersCostume ON Theater.id = TheatersCostume.theater_id
                WHERE 1 = 1' . $filtro_theaters . ' order by Theater.start_date ASC';

        $res_theaters = $this->Theater->query($sql_theaters);

        //ahora armo bien el array de datos
        $array_theaters = array();
        foreach ($res_theaters as $theater) {
            $theater_id = $theater['Theater']['id'];
            $theaterscostume_id = $theater['TheatersCostume']['id'];
            $theatersemployee_id = $theater['TheatersEmployee']['id'];

            if (!isset($array_theaters[$theater_id])) {
                $array_theaters[$theater_id]['Theater'] = $theater['Theater'];
            }

            if (!isset($array_theaters[$theater_id]['Theater']['TheatersCostume'][$theaterscostume_id])) {
                $array_theaters[$theater_id]['Theater']['TheatersCostume'][$theaterscostume_id] = $theater['TheatersCostume'];
            }

            if (!isset($array_theaters[$theater_id]['Theater']['TheatersEmployee'][$theatersemployee_id])) {
                $array_theaters[$theater_id]['Theater']['TheatersEmployee'][$theatersemployee_id] = $theater['TheatersEmployee'];
            }
        }

        //anotaciones
        $sql_anotations = 'SELECT *
                FROM anotations as Anotation
                WHERE 1 = 1' . $filtro_anotations . ' order by Anotation.start_date ASC';

        $array_anotations = array();
        //$array_anotations = $this->Anotation->query($sql_anotations); saco el array de anotaciones porque no quiere que se vea mas

        //bueno bueno bueno, ahora hay que meter todo en un solo array que va a tener el siguiente formato
        $cantidad_total_trabajos = 0;
        $array_datos = array();
        foreach ($array_jobs as $job) {
            $array_datos[strtotime($job['Job']['start_date'])]['Jobs'][$job['Job']['id']] = $job;
            $cantidad_total_trabajos++;
        }
        foreach ($array_theaters as $theater) {
            $array_datos[strtotime($theater['Theater']['start_date'])]['Theaters'][$theater['Theater']['id']] = $theater;
            $cantidad_total_trabajos++;
        }
        foreach ($array_anotations as $anotation) {
            $array_datos[strtotime($anotation['Anotation']['start_date'])]['Anotations'][$anotation['Anotation']['id']] = $anotation;
            $cantidad_total_trabajos++;
        }

        $this->set('cantidad_total_trabajos', $cantidad_total_trabajos);

        //lo meto todo en otro array y serializo la info
        $array_aux = array();
        foreach ($array_datos as $dato_id => $dato) {
            $array_aux[$dato_id] = serialize($dato) . '';
        }

        //le aplico una funcion para ordenar
        ksort($array_aux);

        //ahora armo el array des serializando
        $array_todo = array();
        foreach ($array_aux as $aux_id => $aux_data) {
            $array_todo[$aux_id] = unserialize($aux_data);
        }

        $this->set('array_todo', $array_todo);

        $this->Session->write('data_future', $array_todo);

        //seteo a la vista todos los datos que necesito
        //busco todos los peloteros, con toda la informacion
        $peloteros = $this->Job->Pelotero->find('list', array('recursive' => -1, 'order' => array('name' => 'ASC')));
        $this->set(compact('peloteros'));

        //busco todos los empleados
        $empleados = $this->Employee->find('all', array('fields' => array('Employee.first_name', 'Employee.last_name', 'Employee.id'), 'order' => array('first_name' => 'ASC', 'last_name' => 'ASC')));
        $employees = array();
        foreach ($empleados as $emp) {
            $employees[$emp['Employee']['id']] = $emp['Employee']['first_name'] . ' ' . $emp['Employee']['last_name'];
        }
        $this->set(compact('employees'));

        //busco todos los trajes
        $costumes = $this->Costume->find('list');
        $this->set(compact('costumes'));

        //busco todos las obras
        $productions = $this->Production->find('list');
        $this->set(compact('productions'));

        //busco todos los servicios
        $services = $this->Service->find('list');
        $this->set(compact('services'));

        //busco todos los shows
        $shows = $this->Show->find('list');
        $this->set(compact('shows'));
    }

    function imprimir() {

        Configure::write('debug', 0);
        $this->layout = 'ajax';

        $array_todo = $this->Session->read('data_future');

        //busco todos los peloteros, con toda la informacion
        $peloteros = $this->Job->Pelotero->find('list', array('recursive' => -1, 'order' => array('name' => 'ASC')));

        //busco todos los empleados
        $empleados = $this->Employee->find('all', array('fields' => array('Employee.first_name', 'Employee.last_name', 'Employee.id'), 'order' => array('first_name' => 'ASC', 'last_name' => 'ASC')));
        $employees = array();
        foreach ($empleados as $emp) {
            $employees[$emp['Employee']['id']] = $emp['Employee']['first_name'] . ' ' . $emp['Employee']['last_name'];
        }

        //busco todos los trajes
        $costumes = $this->Costume->find('list');

        //busco todos las obras
        $productions = $this->Production->find('list');

        //busco todos los servicios
        $services = $this->Service->find('list');

        //busco todos los shows
        $shows = $this->Show->find('list');

        //require(SITE_PATH . "/app/vendors/fpdf/fpdf.php");
        App::import('Vendor', 'WellNamed', array('file' => 'fpdf' . DS . 'fpdf.php'));


        $pdf = new PDF();
        $pdf->AliasNbPages();
        $pdf->AddPage();
//        $pdf->SetFont('Arial', 'B', 10);
        $pdf->SetFont('Arial', '', 10);

        $margen_arriba = 12;
        $margen_izquierdo = 12;
        $margen_derecho = 12;
        $pdf->SetTopMargin($margen_arriba);
        $pdf->SetLeftMargin($margen_izquierdo);
        $pdf->SetRightMargin($margen_derecho);

        //defino el salto de linea
        $salto_linea = 0;
        $salto_trabajo = 1;

        //defino el alto de cada linea
        $alto_linea = 4;

        $tipos_tareas = array('show' => 'Show', 'reception' => 'Presentación', 'animation' => 'Animación', 'production' => 'Obra', 'service' => 'Servicios');
        $i = 0;
        foreach ($array_todo as $todo) {

            if (isset($todo['Theaters'])) {

                //EMPIEZA LA PARTE DE THEATERS

                $empleados_usados = array();
                $trajes_usados = array();
                foreach ($todo['Theaters'] as $theater) {

                    $pdf->MultiCell(0, $alto_linea, iconv('utf-8', 'ISO-8859-1', 'Obra de Teatro: ' . $theater['Theater']['name']));
                    $pdf->Ln($salto_linea);
                    $pdf->Cell(20, $alto_linea, date('d/m/Y', strtotime($theater['Theater']['start_date'])));
                    $pdf->Cell(30, $alto_linea, date('H:i', strtotime($theater['Theater']['start_date'])) . ' - ' . date('H:i', strtotime($theater['Theater']['finish_date'])));
                    $pdf->Ln($alto_linea);
                    $pdf->MultiCell(0, $alto_linea, iconv('utf-8', 'ISO-8859-1', 'Dirección: ' . $theater['Theater']['address'] . ' Teléfonos: ' . $theater['Theater']['phone_number'] . ' - ' . $theater['Theater']['movil_number']));

                    if (isset($theater['Theater']['TheatersEmployee'])) {
                        foreach ($theater['Theater']['TheatersEmployee'] as $emp) {
                            if (!empty($emp['employee_id'])) {
                                $empleados_usados[$emp['employee_id']] = $employees[$emp['employee_id']];
                            }
                        }
                    }
                    if (isset($theater['Theater']['TheatersCostume'])) {
                        foreach ($theater['Theater']['TheatersCostume'] as $costume) {
                            if (!empty($costume['costume_id'])) {
                                $trajes_usados[$costume['costume_id']] = $costumes[$costume['costume_id']];
                            }
                        }
                    }
                    $pdf->Ln($salto_linea);
                    $pdf->MultiCell(0, $alto_linea, iconv('utf-8', 'ISO-8859-1', 'Trajes: ' . implode(', ', $trajes_usados)));
                    $pdf->Ln($salto_linea);
                    $pdf->MultiCell(0, $alto_linea, iconv('utf-8', 'ISO-8859-1', 'Empleados: ' . implode(', ', $empleados_usados)));
                    if ($theater['Theater']['description'] != '') {
                        $pdf->Ln($salto_linea);
                        $pdf->MultiCell(0, $alto_linea, iconv('utf-8', 'ISO-8859-1', 'Notas: ' . $theater['Theater']['description']));
                    }
                    $pdf->Ln($salto_trabajo);
                    //obtengo el valor de ubicacion vertical
                    $y = $pdf->GetY();
                    $pdf->Line($margen_izquierdo, $y, 200, $y);
                    $pdf->Ln($salto_trabajo);
                }
            }

            //TERMINA LA PARTE DE THEATERS
            //si tiene trabajos
            if (isset($todo['Jobs'])) {

                //EMPIEZA LA PARTE DE JOBS

                $empleados_usados = array();
                $trajes_usados = array();
                foreach ($todo['Jobs'] as $job) {

                    //voy a armar un array con los shows, uno con las recepciones, animació, servicios y obras
                    $array_cosas = array();
                    foreach ($job['Job']['JobsDetail'] as $jobs_detail) {
                        $tipo = $jobs_detail['type'];
                        $array_cosas[$tipo][$jobs_detail['id']] = $jobs_detail;
                    }

                    $edad = $job['Job']['age'] != NULL ? $job['Job']['age'] . ' años' : '';
                    $tipo = $job['Job']['type'] == 'event' ? 'Evento: ' . $job['Job']['event_name'] : 'Cumpleaños: ' . $job['Job']['birthday_name'] . ' ' . $edad;
                    if (isset($peloteros[$job['Job']['pelotero_id']])) {
                        $tipo .= '  ||  Pelotero: ' . $peloteros[$job['Job']['pelotero_id']];
                    }
                    $pdf->MultiCell(0, $alto_linea, iconv('utf-8', 'ISO-8859-1', $tipo));
                    $pdf->Ln($salto_linea);
                    $pdf->Cell(20, $alto_linea, iconv('utf-8', 'ISO-8859-1', date('d/m/Y', strtotime($job['Job']['start_date']))));
                    $pdf->Cell(30, $alto_linea, iconv('utf-8', 'ISO-8859-1', date('H:i', strtotime($job['Job']['start_date'])) . ' - ' . date('H:i', strtotime($job['Job']['finish_date']))));
                    $pdf->Ln($alto_linea);
                    $pdf->MultiCell(0, $alto_linea, iconv('utf-8', 'ISO-8859-1', 'Dirección: ' . $job['Job']['address'] . ' Teléfonos: ' . $job['Job']['phone_number'] . ' - ' . $job['Job']['movil_number']));
                    $pdf->Ln($salto_linea);

                    $texto_salida = '';
                    $empleados_usados = array();
                    $trajes_usados = array();
                    foreach ($array_cosas as $tarea_type => $tarea) {
                        $texto_salida = $tipos_tareas[$tarea_type] . ': ';
                        $aux_cant_emp = 0;
                        foreach ($tarea as $tar) {
                            $texto_salida .=!empty($tar['show_id']) ? $shows[$tar['show_id']] : '';
                            $texto_salida .=!empty($tar['service_id']) ? $services[$tar['service_id']] . ', ' : '';
                            $texto_salida .=!empty($tar['production_id']) ? $productions[$tar['production_id']] : '';

                            foreach ($tar['JobsDetailsEmployee'] as $emp) {
                                if (!empty($emp['employee_id'])) {
                                    $empleados_usados[$emp['employee_id']] = $employees[$emp['employee_id']];
                                    if ($tarea_type == 'animation' || $tarea_type == 'show' || $tarea_type == 'production') {
                                        $aux_cant_emp++;
                                    }
                                } elseif (isset($emp['cost'])) {
                                    //si no esta seteado el id del empleado, pero si el costo
                                    if ($tarea_type == 'animation' || $tarea_type == 'show' || $tarea_type == 'production') {
                                        $aux_cant_emp++;
                                    }
                                }
                                if (!empty($emp['costume_id'])) {
                                    //si es una recepcion anoto el nombre de los trajes
                                    if ($tarea_type == 'reception') {
                                        $texto_salida .= $costumes[$emp['costume_id']] . ', ';
                                    }
                                    $trajes_usados[$emp['costume_id']] = $costumes[$emp['costume_id']];
                                }
                            }
                            if ($tarea_type == 'animation' || $tarea_type == 'show' || $tarea_type == 'production') {
                                $texto_salida .= '(' . $aux_cant_emp . ' P), ';
                            }
                        }
                        //me fijo si termina con una coma
                        $texto_salida = substr($texto_salida, -2, 2) == ', ' ? substr($texto_salida, 0, -2) : $texto_salida;

                        $pdf->MultiCell(0, $alto_linea, iconv('utf-8', 'ISO-8859-1', $texto_salida));
                        $pdf->Ln($salto_linea);
                    }
                    $pdf->MultiCell(0, $alto_linea, iconv('utf-8', 'ISO-8859-1', 'Trajes: ' . implode(', ', $trajes_usados)));
                    $pdf->Ln($salto_linea);
                    $pdf->MultiCell(0, $alto_linea, iconv('utf-8', 'ISO-8859-1', 'Empleados: ' . implode(', ', $empleados_usados)));
                    $pdf->Ln($salto_linea);
                    $pdf->MultiCell(0, $alto_linea, iconv('utf-8', 'ISO-8859-1', 'Costo: $' . $job['Job']['total_cost']));
                    $pdf->Ln($salto_linea);
                    if ($job['Job']['sign'] != NULL) {
                        $pdf->MultiCell(0, $alto_linea, iconv('utf-8', 'ISO-8859-1', 'Seña: $' . $job['Job']['sign']));
                    }

                    if ($job['Job']['description'] != '') {
                        $pdf->Ln($salto_linea);
                        $pdf->MultiCell(0, $alto_linea, iconv('utf-8', 'ISO-8859-1', 'Notas: ' . $job['Job']['description']));
                    }
                    $pdf->Ln($salto_trabajo);
                    //obtengo el valor de ubicacion vertical
                    $y = $pdf->GetY();
                    $pdf->Line($margen_izquierdo, $y, 200, $y);
                    $pdf->Ln($salto_trabajo);
                }
                //TERMINA LA PARTE DE JOBS
            }

            //si tiene anotaciones
            if (isset($todo['Anotations'])) {

                //EMPIEZA LA PARTE DE ANOTATIONS

                foreach ($todo['Anotations'] as $anotation) {

                    $pdf->MultiCell(0, $alto_linea, iconv('utf-8', 'ISO-8859-1', 'Anotación'));
                    $pdf->Ln($salto_linea);
                    $pdf->Cell(20, $alto_linea, iconv('utf-8', 'ISO-8859-1', date('d/m/Y', strtotime($anotation['Anotation']['start_date']))));
                    $pdf->Cell(30, $alto_linea, iconv('utf-8', 'ISO-8859-1', date('H:i', strtotime($anotation['Anotation']['start_date'])) . ' - ' . date('H:i', strtotime($job['Job']['finish_date']))));
                    $pdf->Ln($alto_linea);
                    $pdf->MultiCell(0, $alto_linea, iconv('utf-8', 'ISO-8859-1', $anotation['Anotation']['description']));
                    $pdf->Ln($salto_linea);
                }
                //TERMINA LA PARTE DE ANOTATIONS
            }
        }

        $pdf->Output();
        die;
    }

    function por_dia($var_start_date = null, $print = null) {
        $this->Job->recursive = 0;
        $this->Theater->recursive = 1;

        $sql_jobs = "SELECT *
                FROM jobs as Job
                LEFT JOIN jobs_details as JobsDetail ON Job.id = JobsDetail.job_id
                LEFT JOIN jobs_details_employees as JobsDetailsEmployee ON JobsDetail.id = JobsDetailsEmployee.jobs_detail_id
                WHERE 1=1";

        $filtro_jobs = '';
        $filtro_theaters = '';
        $filtro_anotations = '';
        $fecha_min = '';
        $fecha_max = '';

        //si vienen filtros aplicados
        if (!empty($this->data)) {

            $datos = $this->data['Future'];

            if (isset($datos['date_from']) && trim($datos['date_from']) != '') {
                list($d, $m, $a) = explode("/", $datos['date_from']);
                $datos['date_from'] = $a . "-" . $m . "-" . $d . ' 00:00:00';
                $datos['date_to'] = $a . "-" . $m . "-" . $d . ' 23:59:59';

                $filtro_jobs .= ' AND Job.start_date >= "' . $datos['date_from'] . '"';
                $filtro_jobs .= ' AND Job.start_date <= "' . $datos['date_to'] . '"';
                $filtro_theaters .= ' AND Theater.start_date >= "' . $datos['date_from'] . '"';
                $filtro_theaters .= ' AND Theater.start_date <= "' . $datos['date_to'] . '"';
                $filtro_anotations .= ' AND Anotation.start_date >= "' . $datos['date_from'] . '"';
                $filtro_anotations .= ' AND Anotation.start_date <= "' . $datos['date_to'] . '"';
                $fecha_min = 'si';
            }

            //guardo el filtro usado en session para despues recordarlo
            $restricciones['Job'] = $filtro_jobs;
            $restricciones['Theater'] = $filtro_theaters;
            $restricciones['Anotation'] = $filtro_anotations;
            $restricciones['data'] = $this->data;
            $this->Session->write('search_conditions_future_por_dia', $restricciones);
        } elseif ($var_start_date != NULL) {
            //si viene la variable $var_start_date, entonces se lo pongo en el this->data

            $aux_fecha_min = date('Y-m-d 00:00:00', $var_start_date);
            $aux_fecha_max = date('Y-m-d 23:59:59', $var_start_date);
            $filtro_jobs .= ' AND Job.start_date >= "' . $aux_fecha_min . '"';
            $filtro_jobs .= ' AND Job.start_date <= "' . $aux_fecha_max . '"';
            $filtro_theaters .= ' AND Theater.start_date >= "' . $aux_fecha_min . '"';
            $filtro_theaters .= ' AND Theater.start_date <= "' . $aux_fecha_max . '"';
            $filtro_anotations .= ' AND Anotation.start_date >= "' . $aux_fecha_min . '"';
            $filtro_anotations .= ' AND Anotation.start_date <= "' . $aux_fecha_max . '"';

            $this->data['Future']['date_from'] = date('d/m/Y', $var_start_date);
            $fecha_min = 'si';
        } elseif ($this->Session->check('search_conditions_future_por_dia')) {

            $restricciones = $this->Session->read('search_conditions_future_por_dia');
            $filtro_jobs = $restricciones['Job'];
            $filtro_theaters = $restricciones['Theater'];
            $filtro_anotations = $restricciones['Anotation'];
            $this->data = $restricciones['data'];
            $datos = $this->data['Future'];

            if (isset($datos['date_from']) && trim($datos['date_from']) != '') {
                $fecha_min = 'si';
            }
        }

        //si no viene ningun filtro de fecha, le pongo lo del día actual
        if ($fecha_min != 'si') {
            $aux_fecha_min = date('Y-m-d 00:00:00');
            $aux_fecha_max = date('Y-m-d 23:59:59');
            $filtro_jobs .= ' AND Job.start_date >= "' . $aux_fecha_min . '"';
            $filtro_jobs .= ' AND Job.start_date <= "' . $aux_fecha_max . '"';
            $filtro_theaters .= ' AND Theater.start_date >= "' . $aux_fecha_min . '"';
            $filtro_theaters .= ' AND Theater.start_date <= "' . $aux_fecha_max . '"';
            $filtro_anotations .= ' AND Anotation.start_date >= "' . $aux_fecha_min . '"';
            $filtro_anotations .= ' AND Anotation.start_date <= "' . $aux_fecha_max . '"';

            $this->data['Future']['date_from'] = date('d/m/Y', strtotime($aux_fecha_min));
        }

        $sql_jobs .= $filtro_jobs . ' order by Job.start_date ASC, Job.type DESC';

//        pr($sql_jobs);
//        die;

        $res_jobs = $this->Job->query($sql_jobs);

        //ahora armo bien el array de datos
        $array_jobs = array();
        foreach ($res_jobs as $job) {
            $job_id = $job['Job']['id'];
            $jobsdetail_id = $job['JobsDetail']['id'];
            $jobsdetailsemployee_id = $job['JobsDetailsEmployee']['id'];

            if (!isset($array_jobs[$job_id])) {
                $array_jobs[$job_id]['Job'] = $job['Job'];
            }

            if (!isset($array_jobs[$job_id]['Job']['JobsDetail'][$jobsdetail_id])) {
                $array_jobs[$job_id]['Job']['JobsDetail'][$jobsdetail_id] = $job['JobsDetail'];
            }

            if (!isset($array_jobs[$job_id]['Job']['JobsDetail'][$jobsdetail_id]['JobsDetailsEmployee'][$jobsdetailsemployee_id])) {
                $array_jobs[$job_id]['Job']['JobsDetail'][$jobsdetail_id]['JobsDetailsEmployee'][$jobsdetailsemployee_id] = $job['JobsDetailsEmployee'];
            }
        }
//        $this->set('jobs', $array_jobs);
        //obras de teatro
        $sql_theaters = 'SELECT *
                FROM theaters as Theater
                LEFT JOIN theaters_employees as TheatersEmployee ON Theater.id = TheatersEmployee.theater_id
                LEFT JOIN theaters_costumes as TheatersCostume ON Theater.id = TheatersCostume.theater_id
                WHERE 1 = 1' . $filtro_theaters . ' order by Theater.start_date ASC';

        $res_theaters = $this->Theater->query($sql_theaters);

        //ahora armo bien el array de datos
        $array_theaters = array();
        foreach ($res_theaters as $theater) {
            $theater_id = $theater['Theater']['id'];
            $theaterscostume_id = $theater['TheatersCostume']['id'];
            $theatersemployee_id = $theater['TheatersEmployee']['id'];

            if (!isset($array_theaters[$theater_id])) {
                $array_theaters[$theater_id]['Theater'] = $theater['Theater'];
            }

            if (!isset($array_theaters[$theater_id]['Theater']['TheatersCostume'][$theaterscostume_id])) {
                $array_theaters[$theater_id]['Theater']['TheatersCostume'][$theaterscostume_id] = $theater['TheatersCostume'];
            }

            if (!isset($array_theaters[$theater_id]['Theater']['TheatersEmployee'][$theatersemployee_id])) {
                $array_theaters[$theater_id]['Theater']['TheatersEmployee'][$theatersemployee_id] = $theater['TheatersEmployee'];
            }
        }

        //anotaciones
        $sql_anotations = 'SELECT *
                FROM anotations as Anotation
                WHERE 1 = 1' . $filtro_anotations . ' order by Anotation.start_date ASC';

        $array_anotations = $this->Anotation->query($sql_anotations);

        //bueno bueno bueno, ahora hay que meter todo en un solo array que va a tener el siguiente formato
        $cantidad_total_trabajos = 0;
        $array_datos = array();
        foreach ($array_jobs as $job) {
            $array_datos[strtotime($job['Job']['start_date'])]['Jobs'][$job['Job']['id']] = $job;
            $cantidad_total_trabajos++;
        }
        foreach ($array_theaters as $theater) {
            $array_datos[strtotime($theater['Theater']['start_date'])]['Theaters'][$theater['Theater']['id']] = $theater;
            $cantidad_total_trabajos++;
        }
        foreach ($array_anotations as $anotation) {
            $array_datos[strtotime($anotation['Anotation']['start_date'])]['Anotations'][$anotation['Anotation']['id']] = $anotation;
            $cantidad_total_trabajos++;
        }

        $this->set('cantidad_total_trabajos', $cantidad_total_trabajos);

        //lo meto todo en otro array y serializo la info
        $array_aux = array();
        foreach ($array_datos as $dato_id => $dato) {
            $array_aux[$dato_id] = serialize($dato) . '';
        }

        //le aplico una funcion para ordenar
        ksort($array_aux);

        //ahora armo el array des serializando
        $array_nuevo = array();
        foreach ($array_aux as $aux_id => $aux_data) {
            $array_nuevo[$aux_id] = unserialize($aux_data);
        }

//        pr($array_nuevo);
//        die;
        //aca lo tengo ordenado por fecha entera, ahora lo voy dividiendo para dejarlo por hora y despues por minuto
        $array_todo = array();
        foreach ($array_nuevo as $fecha => $datos) {
            $i = 0;
            $hora = date('H', $fecha);

            if (isset($datos['Jobs'])) {

                foreach ($datos['Jobs'] as $job) {
                    $i++;

                    $minute = date('i', strtotime($job['Job']['start_date']));
                    $array_aux = array();
                    $array_aux['inicio'] = $job['Job']['start_date'];
                    $array_aux['fin'] = $job['Job']['finish_date'];
                    $array_aux['info'] = $job;

                    $array_todo[$hora][$minute][] = $array_aux;
                }
            }
            if (isset($datos['Theaters'])) {
                foreach ($datos['Theaters'] as $theater) {
                    $i++;

                    $minute = date('i', strtotime($theater['Theater']['start_date']));
                    $array_aux = array();
                    $array_aux['inicio'] = $theater['Theater']['start_date'];
                    $array_aux['fin'] = $theater['Theater']['finish_date'];
                    $array_aux['info'] = $theater;

                    $array_todo[$hora][$minute][] = $array_aux;
                }
            }
            if (isset($datos['Anotations'])) {
                foreach ($datos['Anotations'] as $anotation) {
                    $i++;

                    $minute = date('i', strtotime($anotation['Anotation']['start_date']));
                    $array_aux = array();
                    $array_aux['inicio'] = $anotation['Anotation']['start_date'];
                    $array_aux['fin'] = $anotation['Anotation']['finish_date'];
                    $array_aux['info'] = $anotation;

                    $array_todo[$hora][$minute][] = $array_aux;
                }
            }
        }

        //voy a ir cargando en este array, todos los horarios que ya fueron utilizados
        $minutes = array('00' => '00', '30' => '30');
        $array_registro_tiempos = array();
        $array_registro_empiezan = array();
        $tiempo_dif_aux = 0;
        foreach ($array_todo as $hora_id => $hora) {
            foreach ($minutes as $min) {
                if (isset($hora[$min]) && !empty($hora[$min])) {
                    //si esta esta fecha de inicio, ahora me fijo cuales otra abarca y las cargo todas en el array
                    foreach ($hora[$min] as $minute) {
                        $tiempo_dif_aux = (strtotime($minute['fin']) - strtotime($minute['inicio'])) / 60; //diferencia de tiempos en minutos
                        $cantidad_bloques = $tiempo_dif_aux / 30;

                        if (isset($array_registro_tiempos[date('Hi', strtotime($minute['inicio']))])) {
                            $array_registro_tiempos[date('Hi', strtotime($minute['inicio']))] = $array_registro_tiempos[date('Hi', strtotime($minute['inicio']))] + 1;
                        } else {
                            $array_registro_tiempos[date('Hi', strtotime($minute['inicio']))] = 1;
                        }

                        if (isset($array_registro_empiezan[date('Hi', strtotime($minute['inicio']))])) {
                            $array_registro_empiezan[date('Hi', strtotime($minute['inicio']))] = $array_registro_empiezan[date('Hi', strtotime($minute['inicio']))] + 1;
                        } else {
                            $array_registro_empiezan[date('Hi', strtotime($minute['inicio']))] = 1;
                        }

                        if ($cantidad_bloques > 1) {
                            $w = 1;
                            for ($w; $w < $cantidad_bloques; $w++) {
                                $nuevo_tiempo = strtotime($minute['inicio']) + ($w * 30 * 60);
                                if (isset($array_registro_tiempos[date('Hi', $nuevo_tiempo)])) {
                                    $array_registro_tiempos[date('Hi', $nuevo_tiempo)] = $array_registro_tiempos[date('Hi', $nuevo_tiempo)] + 1;
                                } else {
                                    $array_registro_tiempos[date('Hi', $nuevo_tiempo)] = 1;
                                }
                            }
                        }
                    }
                }
            }
        }

        $this->set('array_registro_tiempos', $array_registro_tiempos);
        $this->set('array_registro_empiezan', $array_registro_empiezan);

        $minimo = '0800';
        $maximo = '0800';
        $i = 0;
        foreach ($array_registro_tiempos as $tiempo => $cant) {
            $i++;
            if ($i == 1) {
                $minimo = $tiempo;
            }
            $maximo = $tiempo;
        }

        $this->set('minimo_tiempos', $minimo);
        $this->set('maximo_tiempos', $maximo);

//        pr($array_registro_tiempos);
//        pr($array_registro_empiezan);
//        die;

        $max = 1;
        if (!empty($array_registro_tiempos)) {
            $max = max($array_registro_tiempos);
        }
        $this->set('array_registro_tiempos_max', $max);

//        pr($array_registro_tiempos);
//        die;

        $w = 8;
        $array_ultimo = array();
        for ($w; $w < 24; $w++) {
            $hora = $w <= 9 ? '0' . $w : $w . '';
            if (!isset($array_todo[$hora])) {
                $array_ultimo[$hora] = array();
            } else {
                $array_ultimo[$hora] = $array_todo[$hora];
            }
        }

        $this->set('array_todo', $array_ultimo);

        //seteo la fecha para un campo oculto
        list($d, $m, $a) = explode("/", $this->data['Future']['date_from']);
        $fecha_aux = $a . "-" . $m . "-" . $d;
        $this->set('fecha_dia', $fecha_aux);

//        pr($array_ultimo);
//        die;
        //seteo a la vista todos los datos que necesito
        //busco todos los peloteros, con toda la informacion
        $peloteros = $this->Job->Pelotero->find('list', array('recursive' => -1, 'order' => array('name' => 'ASC')));
        $this->set(compact('peloteros'));

        //busco todos los empleados
        $empleados = $this->Employee->find('all', array('fields' => array('Employee.first_name', 'Employee.last_name', 'Employee.id'), 'order' => array('first_name' => 'ASC', 'last_name' => 'ASC')));
        $employees = array();
        foreach ($empleados as $emp) {
            $employees[$emp['Employee']['id']] = $emp['Employee']['first_name'] . ' ' . $emp['Employee']['last_name'];
        }
        $this->set(compact('employees'));

        //busco todos los trajes
        $costumes = $this->Costume->find('list');
        $this->set(compact('costumes'));

        //busco todos las obras
        $productions = $this->Production->find('list');
        $this->set(compact('productions'));

        //busco todos los servicios
        $services = $this->Service->find('list');
        $this->set(compact('services'));

        //busco todos los shows
        $shows = $this->Show->find('list');
        $this->set(compact('shows'));

        //armo el array con las horas
        $hours = array();
        for ($i = 8; $i <= 23; $i++) {
            if ($i < 10) {
                $value = '0' . $i;
            } else {
                $value = '' . $i;
            }
            $hours[$i] = $value;
        }
        $this->set(compact('hours'));

        $minutes = array(0 => '00', 30 => '30');
        $this->set(compact('minutes'));

        if ($print != NULL) {
            $this->set('print_por_dia', 1);
            $this->layout = 'print_por_dia';
        }
    }

}